package cn.piesat.scanning.aspect.schedulerTask;

import cn.piesat.scanning.dto.SchedulerTaskBaseDTO;
import cn.piesat.scanning.service.DbDmsSchedulerTaskFileRecordService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

@Aspect
@Component
public class SchedulerTaskFileRecordAspect {

    private static final Logger log = LoggerFactory.getLogger(SchedulerTaskFileRecordAspect.class);

    @Autowired
    private DbDmsSchedulerTaskFileRecordService dbDmsSchedulerTaskFileRecordService;

    @Pointcut("@annotation(cn.piesat.scanning.aspect.schedulerTask.SchedulerTaskFileRecord)")
    private void annotationPointCut() {}

    @Around("annotationPointCut()&&@annotation(schedulerTaskFileRecord)")
    public void doAround(ProceedingJoinPoint joinPoint, SchedulerTaskFileRecord schedulerTaskFileRecord) {
        // 获取方法参数
        Map<String, Object> params = getNameAndValue(joinPoint);
        String taskId = (String) params.get(schedulerTaskFileRecord.taskId());
        if (StringUtils.isEmpty(taskId)) {
            throw new RuntimeException("获取taskId为空");
        }
        Object valueObject = params.get(schedulerTaskFileRecord.value());

        List<String> fileNames = null;
        if (valueObject instanceof SchedulerTaskBaseDTO) {
            fileNames = new ArrayList<>(1);
            fileNames.add(((SchedulerTaskBaseDTO) valueObject).getFileName());
        } else if (valueObject instanceof List) {
            fileNames = (List<String>) ((List) valueObject).stream()
                    .map(e -> ((SchedulerTaskBaseDTO) e).getFileName())
                    .collect(toList());
        }

        dbDmsSchedulerTaskFileRecordService.dataExecutionBatch(taskId, fileNames);

        try {
            joinPoint.proceed();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            dbDmsSchedulerTaskFileRecordService.dataResultsBatch(taskId, fileNames, false);
        }

        dbDmsSchedulerTaskFileRecordService.dataResultsBatch(taskId, fileNames, true);
    }

    /**
     * 获取参数Map集合
     * @param joinPoint
     * @return
     */
    Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
        Map<String, Object> param = new HashMap<>();
        Object[] paramValues = joinPoint.getArgs();
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        for (int i = 0, len = paramNames.length; i < len; i++) {
            param.put(paramNames[i], paramValues[i]);
        }
        return param;
    }
}
